package com.wuchao.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;

/**
 * @Author wuchao66
 * @Date 2022/9/19 16:11
 * @PackageName:com.wuchao.util
 * @ClassName: Utils
 * @Description: TODO
 * @Param
 * @Version 1.0
 */
@Component//组件--类与对象属性
@Configuration //配置类-配置工具--分页插件 拦截去器
public class Utils {
    //静态类
    private static SqlSessionFactory sf;//中间人工厂
    //静态块
    static{
        try {
            //把图纸拿到手
            InputStream is= Resources.getResourceAsStream("mybatis-config.xml");
            //找工人来
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //建厂
            sf= sqlSessionFactoryBuilder.build(is);//根据图纸建好
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //出产品
    public static SqlSession getSqlSession(){
       return sf.openSession(true);//工厂直接出产品true默认提交，不想搞2次
    }
    //关闭产品
    public static void closeSqlSession(SqlSession sqlSession){
        if(sqlSession!=null){
            sqlSession.close();
        }
    }
}
